/*
 *  txdnet.cn tonydon
 * 
 */
package txdnet.util.coder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import txdnet.util.Logger;
import txdnet.util.StaticMark;

/**
 * DESede 算法
 * @author txdnet
 */
public final class DESede {
    private DESede() {
    }
    
    private final static String DES = "DESede";
     /**
     * @see 加密
     * @param src 数据源
     * @param key 密钥，长度必须是8的倍数
     * @return	返回加密后的数据
     * @throws Exception
     */
    private static byte[] encrypt(byte[] src, byte[] key) {
        try {
            SecretKey skey = new SecretKeySpec(key, DES);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            return cipher.doFinal(src);
        } catch (Exception e) {
            Logger.error(DESede.class, e.toString());
            return null;
        }
    }

    /**
     * 解密
     *
     * @param src	数据源
     * @param key	密钥，长度必须是8的倍数
     * @return	返回解密后的原始数据 异常返回字节原始数据
     * @throws Exception
     */
    private static byte[] decrypt(byte[] src, byte[] key) {
        try {
            SecretKey skey = new SecretKeySpec(key, DES);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.DECRYPT_MODE, skey);
            return cipher.doFinal(src);
        } catch (Exception e) {
            Logger.error(DESede.class, e.toString());
            return null;
        }
    }

    /**
     * 数据解密
     *
     * @param data
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws Exception {
        if (data == null) {
            return data;
        }
        byte[] b = decrypt(ByteHexUtil.hex2byte(data.getBytes(StaticMark.ENCODING_UTF8)), key.getBytes());
        if (b == null) {
            return null;
        } else {
            return new String(b, StaticMark.ENCODING_UTF8);
        }
    }

    /**
     * 数据加密
     *
     * @param data
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) {
        if (data != null) {
            try {
                return ByteHexUtil.byte2hex(encrypt(data.getBytes(StaticMark.ENCODING_UTF8), key.getBytes()));
            } catch (Exception e) {
                Logger.error(DESede.class, e.toString());
            }
        }
        return null;
    }
    
//    public static void main(String... args) throws Exception{
//        String key = "d622Bd$JkigbUJk$^*)@$MJI";//需要24位
//        String hash ="2213918299993-225490687961";
//        System.out.append(DESede.encrypt(hash, key));
//    }
}